// page-payImg/payImg.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    changeIntoIdentification: '',//转入身份证号
    deviceList: [],
    hiddenmodalput: true,//可以通过hidden是否掩藏弹出框的属性，来指定那个弹出框
    thatIndex: 0,
    device: {},
    falx: true,
    rollOutFactoryNum: '',//转出的设备
    rollOutIdentification: '',//转出设备的选手
    payData: {
      openid: wx.getStorageSync('openid'),
      total_fee: 1,//110000,
      body: "设备转移登记"
    },
    registerName: '',
    wxUser: '',
    rollOutWxUser: '',
    rollOutName: ''
  },

  toIndex: function () {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  updateDeviceImg: function () {
    wx.redirectTo({
      url: '/page-deviceInformationImg/updateDeviceInfoImg/updateDeviceInfoImg'
    })
  },

  wxPay: function () {
    var that = this;
    var factoryNum = that.data.rollOutFactoryNum;
    var identification = that.data.rollOutIdentification
    var changeIntoIdentification = that.data.identification
    wx.request({//先查一下转移表，是否有当前用户和当前设备
      url: app.globalData.requestURL + 'transferLicense/isHaveTransferLicenseByEntity',
      method: 'POST',
      data: {
        factoryNum: factoryNum,
        identification: identification,
        state: '0'
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (resp) {
        if (resp.data.status == '0') {//不存在可以添加付款后开始添加
          wx.showModal({
            title: '设备转入手续费',
            content: '是否付款',
            success: function (res2) {
              if (res2.confirm) {
                app.wxPay(that.data.payData);
                app.prepay_idReadyCallback = prepay_id => {
                  prepayId = prepay_id
                }
                app.signReadyCallback = sign => {
                  that.requestPayment(sign, prepayId, );
                }
              } else if (res2.cancel) {

              }
            }
          })
        } else {
          wx.showToast({
            title: '转移有误！',
            icon: 'loading',
            duration: 2000,
            mask: true//是否显示透明蒙层
          });
        }
      }
    })
  },
  //申请支付
  requestPayment: function (obj, prepayId) {
    var that = this;
    var data = obj;
    var prepay_id = prepayId;
    var factoryNum = that.data.rollOutFactoryNum;
    var identification = that.data.rollOutIdentification
    var changeIntoIdentification = that.data.identification
    wx.requestPayment({
      'timeStamp': data.timeStamp,
      'nonceStr': data.nonceStr,
      'package': data.package,
      'signType': data.signType,
      'paySign': data.paySign,
      'success': function (res) {
        wx.request({
          url: app.globalData.requestURL + 'transferLicense/save',
          method: 'POST',
          data: {
            factoryNum: factoryNum,
            identification: identification,//转出人
            changeIntoIdentification: changeIntoIdentification,//转入人
            state: '0'
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (resp) {
            if (resp.data.status == '0') {
              wx.showToast({
                title: '登记成功！',
                icon: 'success',
                duration: 2000,
                mask: true,
                success: function () {
                  that.messagePull(prepay_id)
                }
              });
              wx.redirectTo({
                url: '/page-wode/deviceInformation/deviceList/deviceList'
              })
            }
          }
        })
      },
      'fail': function (res) {
        wx.showToast({
          title: '付款失败哦！',
          icon: 'loading',
          duration: 2000,
          mask: true,
          success: function () {
          }
        });
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if (wx.getStorageSync('identification') != '') {
      var param = JSON.parse(options.pushParam);//获取由消息推送进来后的参数
      that.setData({
        rollOutFactoryNum: param.factoryNum,//转出车辆的大架号
        rollOutIdentification: param.identification,//转出人身份证号
        changeIntoIdentification: param.changeIntoIdentification,//转出人搜索出的转入人的身份证号
        identification: wx.getStorageSync('identification')//用此小程序的转入人
      });
      wx.setStorageSync("rollOutFactoryNum", that.data.rollOutFactoryNum);
      wx.setStorageSync("rollOutIdentification", that.data.rollOutIdentification);

      if (that.data.changeIntoIdentification != identification) { //判断发送消息的转出人搜到的转入人和收到此消息的用户是否是匹配的用户
        wx.showModal({
          title: '转入人身份不匹配',
          content: '是否去小程序登录',
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '/page-wode/login/login'
              })
            } else if (res.cancel) {
              //console.log('用户点击取消')
            }
          }
        })
      } else {
        wx.request({
          url: app.globalData.requestURL + 'userInfo/' + that.data.rollOutIdentification + '/getUserInfoByCondition',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            if (res.data.status == '0' && res.data.data != null) {
              var registerName = res.data.data[0].registerName; //转入人姓名
              var wxUser = res.data.data[0].wxUser
              that.setData({
                wxUser: wxUser,
                registerName: registerName
              });
              wx.request({
                url: app.globalData.requestURL + 'userInfo/' + that.data.identification + '/getUserInfoByCondition',
                method: 'POST',
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                success: function (res2) {
                  if (res.data.status == '0' && res.data.data != null) {
                    var rollOutName = res.data.data[0].registerName; //转入人姓名
                    var rollOutWxUser = res.data.data[0].wxUser
                    that.setData({
                      rollOutWxUser: rollOutWxUser,
                      rollOutName: rollOutName
                    });
                  }
                }
              })
            }
          }
        })
      }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onShow: function () {
    var that = this;
    if (that.data.rollOutFactoryNum != '') {
      var factoryNum = that.data.rollOutFactoryNum;
      wx.request({
        url: app.globalData.requestURL + 'deviceInformation/deviceInfoPage',
        method: 'GET',
        data: {
          factoryNum: factoryNum
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded' // 默认值
        },
        success: function (res) {
          var device = res.data.data.records;
          if (device != null && device.length > 0) {
            for (var i = 0; i < device.length; i++) {
              if (device[i].machineryType == '1') {
                device[i].machineryType = "挖掘机"
              }
              if (device[i].machineryType == '2') {
                device[i].machineryType = "装载机"
              }
              if (device[i].machineryType == '3') {
                device[i].machineryType = "矿用自卸车"
              }
              if (device[i].machineryType == '4') {
                device[i].machineryType = "推土机"
              }
              if (device[i].machineryType == '5') {
                device[i].machineryType = "压路机"
              }
              if (device[i].machineryType == '6') {
                device[i].machineryType = "平地机"
              }
              if (device[i].machineryType == '7') {
                device[i].machineryType = "混凝土机械"
              }
              if (device[i].machineryType == '8') {
                res.data.data[i].machineryType = "桩工机械"
              }
              if (device[i].machineryType == '9') {
                device[i].machineryType == "凿岩机械"
              }
              if (device[i].maneuver == '0') {
                device[i].maneuver == '轮式'
              }
              if (device[i].maneuver == '1') {
                device[i].maneuver == '履带'
              }
              if (device[i].fuel == '0') {
                device[i].fuel == '柴油'
              }
              if (device[i].fuel == '1') {
                device[i].fuel == '汽油'
              }
              if (device[i].fuel == '2') {
                device[i].fuel == '天然气'
              }
              if (device[i].state == '0') {
                device[i].state == '待审核'
              }
              if (device[i].state == '1') {
                device[i].state == '审核中'
              }
              if (device[i].state == '2') {
                device[i].state == '已审核'
              }
              if (device[i].state == '3') {
                device[i].state == '审核未通过'
              }
              if (device[i].state == '4') {
                device[i].state == '已完成'
              }
              if (device[i].productionType == '0') {
                device[i].productionType == '国产'
              }
              if (device[i].productionType == '1') {
                device[i].productionType == '合资'
              }
              if (device[i].productionType == '2') {
                device[i].productionType == '进口'
              }
              that.setData({ 
                device:device[i]
              });
            }
            that.setData({
              deviceList: res.data.data.records
            });
          }
        }
      })
    }
  },
  /**
   * 设备转移的消息推送
   */
  messagePull: function (e) {
    var that = this;
    var formId = e; //支付号
    //var rollOutIdentification = that.data.rollOutIdentification;//转出单位
    //var identification = that.data.identification;//转入单位
    var wxUser = that.data.wxUser; //转入人微信
    var registerName = that.data. registerName//转入人姓名
    var machineryType = that.data.device.machineryType; //设备类型
    var deviecBrand = that.data.device.deviecBrand; //设备品牌
    var plateSubject = that.data.device.plateSubject; //设备型号
    var rollOutName = that.data.rollOutName; //转出人姓名
    var rollOutWxUser = that.data.rollOutWxUser //转出单位微信
    var factoryNum = that.data.device.factoryNum; //设备大架号
    //var pushParam = '{"factoryNum":"' + factoryNum + '","identification":"' + identification + '","changeIntoIdentification":"' + changeIntoIdentification + '"}';推送消息跳转的页面的参数
    var date = new Date();
    var Y = date.getFullYear();//年 
    //月  
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //日  
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    //时  
    var h = date.getHours();
    //分  
    var m = (date.getMinutes() < 10 ? +date.getMinutes() : date.getMinutes());
    that.setData({
      showModalStatus: false
    })
    var content = JSON.stringify([{
      keyword1: { //申请人
        value: registerName,
        color: "#173177"
      }
    },
    {
      keyword2: {//详情
        value: rollOutName + "的" + deviecBrand + plateSubject + machineryType + "设备已转入贵单位",
        color: "#173177"
      }
    },
    {
      keyword3: {//时间
        value: Y + "年" + M + "月" + D + "日 " + h + ":" + m,
        color: "#173177"
      }
    }]);
    var contentSec = JSON.stringify([{
      keyword1: { //申请人
        value: registerName,
        color: "#173177"
      }
    },
    {
      keyword2: {//详情
        value: registerName + "已完成" + deviecBrand + plateSubject + machineryType + "设备已转入手续",
        color: "#173177"
      }
    },
    {
      keyword3: {//时间
        value: Y + "年" + M + "月" + D + "日 " + h + ":" + m,
        color: "#173177"
      }
    }]);
    wx.request({
      url: app.globalData.requestURL + 'wxMessage/pushMessage',//发送模版消息
      //
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        touser: wxUser,//接收消息的用户
        template_id: "_-dTL2OwXZJDsRDymy4I4K3HS2-v-GH27pQyV-_jWw4",
        page: "/page-wode/deviceInformation/deviceList/deviceList",
        form_id: formId,
        content, content
        //emphasis_keyword: "keyword1.DATA"
      },
      success: function (resmsg) {
        var errcode = resmsg.data.data.errcode
        // console.log("消息推送的返回值 " + errcode)
        if (errcode == 0 || errcode == '0') {
          wx.showToast({
            title: '通知已发出',
            icon: 'success',
            duration: 2000,
            mask: true
          });
        }
      }
    })
    //向转出人发送消息
    wx.request({
      url: app.globalData.requestURL + 'wxMessage/pushMessage',//发送模版消息
      //
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        touser: rollOutWxUser,
        template_id: "_-dTL2OwXZJDsRDymy4I4K3HS2-v-GH27pQyV-_jWw4",
        page: "/page-wode/deviceInformation/deviceList/deviceList",
        form_id: formId,
        content, contentSec
        //emphasis_keyword: "keyword1.DATA"
      },
      success: function (resmsg) {

        var errcode = resmsg.data.data.errcode
        // console.log("消息推送的返回值 " + errcode)
        if (errcode == 0 || errcode == '0') {
          wx.showToast({
            title: '通知已发出',
            icon: 'success',
            duration: 2000,
            mask: true
          });
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})